import { defineStore } from 'pinia'
import taskApi from '@/api/task'

export const useTaskStore = defineStore('task', {
  state: () => ({
    tasks: [],
    currentTask: null,
    loading: false,
    error: null,
    filters: {
      status: '',
      stream_id: '',
      page: 1,
      limit: 20
    },
    total: 0,
    stats: {
      total: 0,
      running: 0,
      pending: 0,
      completed: 0,
      failed: 0,
      error: 0,
      cancelled: 0
    },
    retryStats: {
      total_tasks_with_retries: 0,
      total_retries: 0,
      average_retries: 0,
      max_retries: 0
    }
  }),

  getters: {
    filteredTasks: (state) => {
      let result = state.tasks
      if (state.filters.status) {
        result = result.filter(task => task.status === state.filters.status)
      }
      if (state.filters.stream_id) {
        result = result.filter(task => task.stream_id === parseInt(state.filters.stream_id))
      }
      return result
    },

    runningTasks: (state) => state.tasks.filter(task => task.status === 'running'),
    failedTasks: (state) => state.tasks.filter(task => task.status === 'error' || task.status === 'failed'),
    
    retrySummary: (state) => {
      return {
        totalRetries: state.retryStats.total_retries,
        failedWithRetries: state.retryStats.total_tasks_with_retries,
        maxRetries: state.retryStats.max_retries
      }
    }
  },

  actions: {
    async fetchTasks() {
      this.loading = true
      this.error = null
      
      try {
        const params = new URLSearchParams()
        if (this.filters.status) params.append('status', this.filters.status)
        if (this.filters.stream_id) params.append('stream_id', this.filters.stream_id)
        params.append('page', this.filters.page)
        params.append('limit', this.filters.limit)
        
        const response = await taskApi.getTasks(params)
        this.tasks = response
        this.total = response.length
      } catch (error) {
        this.error = error.response?.data?.detail || '获取任务列表失败'
      } finally {
        this.loading = false
      }
    },

    async fetchTask(id) {
      this.loading = true
      this.error = null
      
      try {
        const response = await taskApi.getTask(id)
        this.currentTask = response
        return response
      } catch (error) {
        this.error = error.response?.data?.detail || '获取任务详情失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    async createTask(taskData) {
      const response = await taskApi.createTask(taskData)
      return response
    },
    

    
    async startTask(id) {
      await taskApi.startTask(id)
    },
    
    async stopTask(id) {
      await taskApi.stopTask(id)
    },
    
    async retryTask(id, force = false) {
      await taskApi.retryTask(id, force)
    },
    
    async deleteTask(id) {
      await taskApi.deleteTask(id)
    },

    async batchStart(taskIds) {
      try {
        const response = await taskApi.batchStart(taskIds)
        
        // 批量更新本地状态
        taskIds.forEach(id => {
          const task = this.tasks.find(t => t.id === id)
          if (task && response.results.find(r => r.task_id === id)?.success) {
            task.status = 'running'
            task.started_at = new Date().toISOString()
          }
        })
        
        await this.fetchStats()
        return response
      } catch (error) {
        throw new Error('批量启动任务失败')
      }
    },

    async batchStop(taskIds) {
      try {
        const response = await taskApi.batchStop(taskIds)
        
        // 批量更新本地状态
        taskIds.forEach(id => {
          const task = this.tasks.find(t => t.id === id)
          if (task && response.results.find(r => r.task_id === id)?.success) {
            task.status = 'cancelled'
            task.completed_at = new Date().toISOString()
          }
        })
        
        await this.fetchStats()
        return response
      } catch (error) {
        throw new Error('批量停止任务失败')
      }
    },

    async fetchStats() {
      try {
        const { stats, retryStats } = await taskApi.fetchStats()
        this.stats = stats
        this.retryStats = retryStats
      } catch (error) {
        console.error('获取统计信息失败:', error)
      }
    },

    async refreshAll() {
      await Promise.all([
        this.fetchTasks(),
        this.fetchStats()
      ])
    },

    setFilter(filterName, value) {
      this.filters[filterName] = value
      this.filters.page = 1
    },

    resetFilters() {
      this.filters = {
        status: '',
        stream_id: '',
        page: 1,
        limit: 20
      }
    },

    async pollTaskStatus() {
      // 定期轮询任务状态
      if (!this.pollingInterval) {
        this.pollingInterval = setInterval(async () => {
          const hasRunningTasks = this.tasks.some(task => task.status === 'running')
          if (hasRunningTasks) {
            await this.fetchTasks()
            await this.fetchStats()
          }
        }, 5000) // 5秒轮询一次
      }
    },

    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval)
        this.pollingInterval = null
      }
    }
  }
})